<template>
  <div class="disease-management">
    <!-- 查询条件区域 -->
    <el-card class="search-card">
      <div class="search-header">
        <span class="title">查询条件</span>
      </div>
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="疾病描述:">
              <el-input v-model="searchForm.description" placeholder="请输入疾病描述" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="疾病名称:">
              <el-input v-model="searchForm.name" placeholder="请输入疾病名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="一级科室:">
              <el-select v-model="searchForm.department" placeholder="请选择科室" clearable>
                <el-option label="全部" value="" />
                <el-option
                    v-for="dept in departments"
                    :key="dept.value"
                    :label="dept.label"
                    :value="dept.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="search-buttons">
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 疾病列表区域 -->
    <el-card class="list-card">
      <div class="list-header">
        <span class="title">疾病列表</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            <span>添加</span>
          </el-button>
          <el-button
              type="danger"
              :disabled="selectedDiseases.length === 0"
              @click="handleBatchDelete"
          >
            <span v-if="selectedDiseases.length > 0">
              已选择{{ selectedDiseases.length }}项，可以进行批量删除
            </span>
            <span v-else>删除</span>
          </el-button>
        </div>
      </div>

      <el-table
          :data="diseaseList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="疾病" width="180" />
        <el-table-column prop="department" label="科室" width="220">
          <template #default="{ row }">
            {{ row.departmentName }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="疾病描述">
          <template #default="{ row }">
            <div class="description">
              {{ row.description }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页插件 ========================================== =============================== -->
    <div class="demo-pagination-block">
      <!--
                  1. current-page  ： 当前页   （重要）
                  2. page-size  : 每页显示条数（重要）
                  3. page-sizes ： 分页类型
                  4. small： 字体大小
                  5. disabled： 是否可用
                  6. background： 按钮颜色
                  7. total： 总数据条数（重要）

          -->
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[2, 3, 4, 5]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 分页插件 ========================================== =============================== -->

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";
import {router} from "@/router/index.js";



// 科室选项
const departments = ref([])
const getDepartments = () => {
  axios.get('/disease/getDiseaseByDepartmentId').then(res => {
    departments.value = res.data.obj.map(item=>({
      value: item.id || item.value || item,
      label:  item.name || item.label || item
    }))
  })
}
// 分页模型定义=======================================================================
let pageNum = ref(1);
let pageSize = ref(3);
let total = ref(1);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const handleSizeChange = (val) => {
  pageSize.value = val;
  getDiseaseList();
}
const handleCurrentChange = (val) => {
  // 将这个val数字赋值给 pageNum
  pageNum.value = val;
  getDiseaseList();
}
// 分页模型定义=======================================================================


// 疾病列表数据
const diseaseList = ref([])
const getDiseaseList=()=>{
  axios.get(`/disease/getDisease/${pageNum.value}/${pageSize.value}`).then(res => {
    diseaseList.value = res.data.obj.data;
    total.value = res.data.obj.total;
    ElMessage.success('查询成功')
  })
}

// 选中的疾病
const selectedDiseases = ref([])

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedDiseases.value = selection
}

// 查询表单
const searchForm = ref({})
// 条件查询
const handleSearch = () => {
  axios.post(`/disease/searchDisease/${pageNum.value}/${pageSize.value}`,searchForm.value).then(res => {
    diseaseList.value = res.data.obj.data;
    total.value = res.data.obj.total;
    ElMessage.success('查询成功')
  })
  ElMessage.success('查询成功')
  // 这里实际调用API查询
  console.log('查询条件:', searchForm.value)
}

// 重置查询
const resetSearch = () => {
  searchForm.value = {
    doctorName: '',
    hospitalName: '',
    department: ''
  }
  handleSearch()
}

// 添加疾病
const handleAdd = () => {
  router.push({
    name: 'updateDisease',
  })
}
// 编辑疾病
const handleEdit = (row) => {
  router.push({
    name: 'updateDisease',
    params: {
      id: row.id
    }
  })
}

// 删除疾病=============================================================
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除疾病 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/disease/deleteDisease/${row.id}`).then(res=>{
      ElMessage.success('删除成功')
      getDiseaseList();
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedDiseases.value.length === 0) return
  ElMessageBox.confirm(`确定要删除选中的 ${selectedDiseases.value.length} 项疾病吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedDiseases.value.map(item => item.id)
    axios.post(`/disease/batchDeleteDisease`,ids).then(res=>{
      ElMessage.success('批量删除成功')
      getDiseaseList();
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

onMounted(() => {
  getDiseaseList();
  getDepartments();
})
</script>

<style scoped>
.disease-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-header .title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.list-card {
  margin-bottom: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-header .title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.description {
  white-space: pre-line;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}
</style>